using System;
using System.CodeDom;

namespace Objectinator
{
    public class Field
    {
        private readonly Visibility visibility;
        private readonly Type type;
        private readonly string name;
        private readonly bool withAccessors;

        public Field(Visibility visibility, Type type, string name, bool withAccessors)
        {
            this.visibility = visibility;
            this.type = type;
            this.name = name;
            this.withAccessors = withAccessors;
        }

        public void AddDeclaration(CodeTypeDeclaration typeDeclaration)
        {
            CodeMemberField member = new CodeMemberField();
            member.Name = name;
            member.Attributes = (MemberAttributes) visibility;
            member.Type = new CodeTypeReference(type);
            typeDeclaration.Members.Add(member);
            if (withAccessors)
            {
                CodeMemberProperty property = new CodeMemberProperty();
                property.Name = char.ToUpper(name[0]) + name.Substring(1);
                property.Type = new CodeTypeReference(type);
                property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                property.HasGet = property.HasSet = true;
                property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), name)));
                property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), name), new CodePropertySetValueReferenceExpression()));
                typeDeclaration.Members.Add(property);
            }
        }
    }
}